package com.link.base.base.buryingpoint.buriedcode.controller;

import com.alibaba.fastjson.JSONObject;
import com.link.base.base.buryingpoint.buriedcode.model.BuriedCode;
import com.link.base.base.buryingpoint.buriedcode.model.TrackConf;
import com.link.base.base.buryingpoint.buriedcode.model.TrackItems;
import com.link.base.base.buryingpoint.buriedcode.service.BuriedCodeService;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.controller.BasicControllerException;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.util.RedisUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 埋点代码-埋点代码
 *
 * @author 秦学刚
 * @date 2019/02/26 09:30
 */
@Controller
@RequestMapping("/link/buriedCode")
public class BuriedCodeController extends BasicController<BuriedCode> {
    /**redis存储配置信息的KEY*/
    private static final String REDIS_TRACK_CONF_KEY = "redis_track_conf";

    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private BuriedCodeService buriedCodeService;

    @Override
    public BasicService<BuriedCode> getBasicService() throws Exception {
        return buriedCodeService;
    }


    /**
     * 埋点批量保存
     *
     * @param list 埋点代码对象
     * @author : qinxuegang
     * @date: 2019/3/7 17:53
     */
    @RequestMapping({"/batchBuriedInsert"})
    @ResponseBody
    public Map<String, Object> batchBuriedInsert(@RequestBody List<BuriedCode> list, HttpSession session, HttpServletRequest request,
                                                 HttpServletResponse response) {
        HashMap result = new HashMap();
        try {
            List<String> ids = new ArrayList<>();
            List<BuriedCode> tempListInsert = new ArrayList<>();
            List<BuriedCode> tempListUpdate = new ArrayList<>();
            for (int i = 0; list != null && i < list.size(); ++i) {
                BuriedCode entity = list.get(i);
                if ("UPDATE".equals(entity.getRow_status())) {
                    this.beforUpdate(entity, request);
                    this.beforUpsert(entity, request);
                    tempListUpdate.add(entity);
                    ids.add(String.valueOf(entity.getId()));
                } else if ("NEW".equals(entity.getRow_status())) {
                    Long tempId = keyGenerateService.keyGenerate();
                    ids.add(String.valueOf(tempId));
                    entity.setId(tempId);
                    this.beforInsert(entity, request);
                    this.beforUpsert(entity, request);
                    // this.auditTrailInsert(entity, request, session, "BN");
                    tempListInsert.add(entity);
                }
            }
            buriedCodeService.batchInsert(tempListInsert);
            buriedCodeService.batchUpdate(tempListUpdate);
            QueryParams qps = new QueryParams();
            qps.setPageFlag(false);
            qps.addFilter(new Filter("id", Filter.OP_IN, ids));
            BuriedCode buriedCode = (BuriedCode) BasicModel.transformClass(BuriedCode.class, qps);
            List<BuriedCode> listBuriedCode = buriedCodeService.queryByExamplePage(buriedCode);
            result.put("success", true);
            result.put("rows", listBuriedCode);
        } catch (BasicServiceException var8) {
            result.put("success", false);
            result.put("result", var8.getMessage());
            result.put("detailMessage", var8.getDetailMessage());
        } catch (Exception var9) {
            result.put("success", false);
            result.put("result", var9.getMessage());
        }
        return result;
    }

    /**
     * 埋点批量保存并生成埋点文件
     *
     * @param list 埋点代码对象
     * @author : qinxuegang
     * @date: 2019/3/7 17:53
     */
    @RequestMapping({"/batchInsertDownload"})
    @ResponseBody
    public Map<String, Object> batchInsertDownload(@RequestBody List<BuriedCode> list, HttpSession session, HttpServletRequest request,
                                                 HttpServletResponse response) {
        HashMap result = new HashMap();
        try {
            List<String> ids = new ArrayList<>();
            List<BuriedCode> tempList = new ArrayList<>();
            for (int i = 0; list != null && i < list.size(); ++i) {
                BuriedCode entity = list.get(i);
                Long tempId = keyGenerateService.keyGenerate();
                ids.add(String.valueOf(tempId));
                entity.setId(tempId);
                this.beforInsert(entity, request);
                this.beforUpsert(entity, request);
                // this.auditTrailInsert(entity, request, session, "BN");
                tempList.add(entity);
            }
            buriedCodeService.batchInsert(tempList);
            QueryParams qps = new QueryParams();
            qps.setPageFlag(false);
            qps.addFilter(new Filter("id", Filter.OP_IN, ids));
            BuriedCode buriedCode = (BuriedCode) BasicModel.transformClass(BuriedCode.class, qps);
            List<BuriedCode> listBuriedCode = buriedCodeService.queryByExamplePage(buriedCode);
            String path = buriedCodeService.batchBuriedDownLoad(listBuriedCode);
            result.put("success", true);
            result.put("result", path);
        } catch (BasicServiceException var8) {
            result.put("success", false);
            result.put("result", var8.getMessage());
            result.put("detailMessage", var8.getDetailMessage());
        } catch (Exception var9) {
            result.put("success", false);
            result.put("result", var9.getMessage());
        }
        return result;
    }

    /**
     * 埋点代码批量导出问题
     *
     * @param list 埋点代码对象
     * @author : qinxuegang
     * @date: 2019/3/7 17:53
     */
    @RequestMapping({"/batchBuriedDownLoad"})
    @ResponseBody
    public Map<String, Object> batchBuriedDownLoad(@RequestBody List<BuriedCode> list, HttpSession session, HttpServletRequest request,
                                                   HttpServletResponse response) {
        HashMap result = new HashMap();
        if (list == null || list.size() <= 0) {
            throw new BasicServiceException("不存在埋点信息");
        }
        try {
            String path = buriedCodeService.batchBuriedDownLoad(list);
            result.put("success", true);
            result.put("result", path);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 埋点信息存储
     *
     * @param json 埋点信息存储对象
     * @author : qinxuegang
     * @date: 2019/3/7 17:53
     */
    @RequestMapping({"/BuriedInfoSave"})
    @ResponseBody
    public Map<String, Object> BuriedInfoSave(String json, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        HashMap result = new HashMap();
        try {
            // 这里使用kafka的方式保存埋码内容
            buriedCodeService.batchBuriedInsert(json, request);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 获取埋点配置信息
     *
     * @param buriedCode 埋点信息存储对象
     * @author : qinxuegang
     * @date: 2019/3/7 17:53
     */
    @RequestMapping({"/getTrackConf"})
    @ResponseBody
    public Map<String, Object> getTrackConf(BuriedCode buriedCode, HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {
        HashMap result = new HashMap();
        LinkRedisClient jedis = null;
        try {
            // 先从缓存中取，无则查询，广告头ID做唯一标识
            jedis = RedisUtil.getJedis();
            String key = getRedisKey(buriedCode);
            String jsonStr = jedis.get(key);
            if (StringUtils.isNotBlank(jsonStr)) {
                TrackConf trackConf = JSONObject.parseObject(jsonStr, TrackConf.class);
                result.put("result", trackConf);
                result.put("success", true);
                return result;
            }
            TrackConf trackConf = refreshConfCache(buriedCode, jedis);
            result.put("result", trackConf);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return result;
    }

    /**
     * 手动刷新缓存
     *
     * @param buriedCode 埋点信息存储对象
     * @author : Ninglanhao
     * @date: 2019/3/7 17:53
     */
    @RequestMapping({"/refreshTrackConfCache"})
    @ResponseBody
    public Map<String, Object> refreshTrackConfCache(@RequestBody BuriedCode buriedCode,
                                                     HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        HashMap result = new HashMap();
        LinkRedisClient jedis = null;
        try {
            jedis = RedisUtil.getJedis();
            this.refreshConfCache(buriedCode, jedis);
            result.put("result", "刷新配置成功");
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return result;
    }


    /**
     * 根据广告ID查询配置，放入redis缓存
     *
     * @author NingLanhao
     * @date 2019-06-17 16:52
     * @param buriedCode 查询参数
     * @param jedis
     * @return com.link.business.base.buryingpoint.buriedcode.model.TrackConf
     */
    private TrackConf refreshConfCache(BuriedCode buriedCode, LinkRedisClient jedis) throws Exception {
        String key = getRedisKey(buriedCode);
        TrackConf trackConf = new TrackConf();
        List<TrackItems> list = new ArrayList<>();
        QueryParams qps = new QueryParams();
        qps.setPageFlag(false);
        qps.addFilter(new Filter("advertisementId", buriedCode.getAdvertisementId()));
        qps.addFilter(new Filter("type", buriedCode.getType()));
        qps.addFilter(new Filter("status", "Y"));
        // 小程序appId不为空则也作为查询条件
        if (StringUtils.isNotBlank(buriedCode.getMiniAppId())) {
            qps.addFilter(new Filter("miniAppId", buriedCode.getMiniAppId()));

        }
        BuriedCode buriedCodeExample = BasicModel.transformClass(BuriedCode.class, qps);
        // buriedCodeExample.setLoginCorpId(0L);
        List<BuriedCode> listBuriedCode = buriedCodeService.queryByExamplePage(buriedCodeExample);
        for (BuriedCode buriedCode1 : listBuriedCode) {
            TrackItems trackItems = new TrackItems();
            trackItems.setId(buriedCode1.getId());
            trackItems.setSelector(buriedCode1.getSelector());
            trackItems.setEventType(buriedCode1.getEventType());
            trackItems.setName(buriedCode1.getName());
            // 小程序埋点时该字段表示对应页面路径
            trackItems.setPath(buriedCode.getGroundPageUrl());
            list.add(trackItems);
        }
        trackConf.setTrackItems(list);
        // 查询后放入缓存
        jedis.set(key, JSONObject.toJSONString(trackConf));
        return trackConf;
    }

    /**
     * 根据广告埋点查询对象，生成缓存key值
     *
     * @author 姚润发
     * @date 2019/07/04
     * @param buriedCode
     * @return
     */
    private String getRedisKey(BuriedCode buriedCode) {
        if (buriedCode != null) {
            if (StringUtils.isBlank(buriedCode.getAdvertisementId())) {
                throw new BasicControllerException("广告头id不能为空");
            }
            if (StringUtils.isBlank(buriedCode.getType())) {
                throw new BasicControllerException("埋点类型不能为空");
            }
            StringBuffer strb = new StringBuffer(REDIS_TRACK_CONF_KEY);
            strb.append("_" + buriedCode.getAdvertisementId());
            strb.append("_" + buriedCode.getType());
            if (StringUtils.isNotBlank(buriedCode.getMiniAppId())) {
                strb.append("_" + buriedCode.getMiniAppId());
            }
            return strb.toString();
        } else {
            throw new BasicControllerException("埋点配置查询对象为空");
        }
    }
}
